/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.toidep.bitmaputil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.toidep.R;
import com.toidep.config.ConfigUtility;
import com.toidep.interfaces.DialogListener;

/**
 * A simple subclass of {@link ImageResizer} that fetches and resizes images
 * fetched from a URL.
 */
@SuppressLint("NewApi")
public class ImageFetcher extends ImageResizer {
	private static final String TAG = "ImageFetcher";
	private static final int HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10MB
	private static final int IO_BUFFER_SIZE = 8 * 1024;

	private DiskLruCache mHttpDiskCache;
	private File mHttpCacheDir;
	private boolean mHttpDiskCacheStarting = true;
	private final Object mHttpDiskCacheLock = new Object();
	private static final int DISK_CACHE_INDEX = 0;

	public static int LAYER_TYPE_NONE = 0;
	public static int LAYER_TYPE_SOFTWARE = 1;
	public static int LAYER_TYPE_HARDWARE = 2;

	public ArrayList<HttpURLConnection> arrConnections = new ArrayList<HttpURLConnection>();

	/**
	 * Initialize providing a target image width and height for the processing
	 * images.
	 * 
	 * @param context
	 * @param imageWidth
	 * @param imageHeight
	 */
	// public ImageFetcher(Context context, int imageWidth, int imageHeight) {
	// super(context, imageWidth, imageHeight);
	// init(context);
	// }

	/**
	 * Initialize providing a single target image size (used for both width and
	 * height);
	 * 
	 * @param context
	 * @param imageSize
	 */
	// public ImageFetcher(Context context, int imageSize) {
	// super(context, imageSize);
	// init(context);
	// }

	public ImageFetcher(Activity context, int imageSize, File cacheDir) {
		super(context, imageSize);
		init(context, cacheDir);
	}

	// private void init(Context context) {
	// checkConnection(context);
	// mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR);
	// }

	private void init(Context context, File cacFile) {
		checkConnection(context);
		mHttpCacheDir = cacFile;
	}
	
	public boolean isExistFile() {
		if (mHttpCacheDir == null) {
			return false;
		}
		return true;
	}

	public void clearFiles() {
		if (mHttpCacheDir == null)
			return;
		try {
			DiskLruCache.deleteContents(mHttpCacheDir);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// File[] files = mHttpCacheDir.listFiles();
		// File[] files1 = .listFiles();
	}

	@Override
	protected void initDiskCacheInternal() {
		final long start = System.currentTimeMillis();
		super.initDiskCacheInternal();
		initHttpDiskCache();
		long end = System.currentTimeMillis();
		Log.e("Time to do init cache", "" + (end - start));
	}

	private void initHttpDiskCache() {

		if (mHttpCacheDir == null) {
			return;
		}

		if (!mHttpCacheDir.exists()) {
			mHttpCacheDir.mkdirs();
		}
		synchronized (mHttpDiskCacheLock) {
			if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) {
				try {
					// Log.e("init SD card", "OK");
					mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE);
					// if (BuildConfig.DEBUG) {
					// Log.e(TAG, "HTTP cache initialized");
					// }
				} catch (IOException e) {
					mHttpDiskCache = null;
					Log.e(TAG, "121 " + e.getCause().toString());
				}
			}
			mHttpDiskCacheStarting = false;
			mHttpDiskCacheLock.notifyAll();
		}
	}

	@Override
	protected void clearCacheInternal() {
		super.clearCacheInternal();
		synchronized (mHttpDiskCacheLock) {
			if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) {
				try {
					mHttpDiskCache.delete();
					// if (BuildConfig.DEBUG) {
					// Log.d(TAG, "HTTP cache cleared");
					// }
				} catch (IOException e) {
					Log.e(TAG, "clearCacheInternal - " + e);
				}
				mHttpDiskCache = null;
				mHttpDiskCacheStarting = true;
				initHttpDiskCache();
			}
		}
	}

	@Override
	protected void flushCacheInternal() {
		super.flushCacheInternal();
		synchronized (mHttpDiskCacheLock) {
			if (mHttpDiskCache != null) {
				try {
					mHttpDiskCache.flush();
					// if (BuildConfig.DEBUG) {
					// Log.e(TAG, "HTTP cache flushed");
					// }
				} catch (IOException e) {
					Log.e(TAG, "flush - " + e);
				}
			}
		}
	}

	@Override
	protected void closeCacheInternal() {
		super.closeCacheInternal();
		synchronized (mHttpDiskCacheLock) {
			if (mHttpDiskCache != null) {
				try {
					if (!mHttpDiskCache.isClosed()) {
						mHttpDiskCache.close();
						mHttpDiskCache = null;
						// if (BuildConfig.DEBUG) {
						// Log.d(TAG, "HTTP cache closed");
						// }
					}
				} catch (IOException e) {
					Log.e(TAG, "closeCacheInternal - " + e);
				}
			}
		}
	}

	/**
	 * Simple network connection check.
	 * 
	 * @param context
	 */
	private void checkConnection(Context context) {
		final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) {
			Toast.makeText(context, R.string.text_no_network, Toast.LENGTH_LONG).show();
			Log.e(TAG, "checkConnection - no connection found");
		}
	}

	/**
	 * The main process method, which will be called by the ImageWorker in the
	 * AsyncTask background thread.
	 * 
	 * @param data
	 *            The data to load the bitmap, in this case, a regular http URL
	 * @return The downloaded and resized bitmap
	 */
	private Bitmap processBitmap(String data, int width, int height, Bitmap noresultBm) {
		// if (BuildConfig.DEBUG) {
		// Log.d(TAG, "processBitmap - " + data);
		// }

		final String key = ImageCache.hashKeyForDisk(data);
		FileDescriptor fileDescriptor = null;
		FileInputStream fileInputStream = null;
		DiskLruCache.Snapshot snapshot;
		// long start = System.currentTimeMillis();
		// long end;
		synchronized (mHttpDiskCacheLock) {
			// Wait for disk cache to initialize
			while (mHttpDiskCacheStarting) {
				try {
					mHttpDiskCacheLock.wait();
				} catch (InterruptedException e) {
				}
			}

			if (mHttpDiskCache != null) {
				try {
					snapshot = mHttpDiskCache.get(key);
					if (snapshot == null) {
						// if (BuildConfig.DEBUG) {
						// Log.d(TAG,
						// "processBitmap, not found in http cache, downloading...");
						// }
						DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
						if (editor != null) {
							// boolean downloadStream =
							// downloadUrlToStream(data,
							// editor.newOutputStream(DISK_CACHE_INDEX);
							// while (downloadUrlToStream(data,
							// editor.newOutputStream(DISK_CACHE_INDEX)) {
							// editor.commit();
							//
							// }
							if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX))) {
								// start = System.currentTimeMillis();
								// Log.e("End load " + data, "" + start);
								editor.commit();
							} else {
								editor.abort();
								Log.e(TAG + " 255 ", "Load fail");
								return noresultBm;
							}
						}
						snapshot = mHttpDiskCache.get(key);
					}
					if (snapshot != null) {
						fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
						fileDescriptor = fileInputStream.getFD();
					}
				} catch (IOException e) {
					Log.e(TAG, "processBitmap - " + e);
				} catch (IllegalStateException e) {
					Log.e(TAG, "processBitmap - " + e);
				} finally {
					if (fileDescriptor == null && fileInputStream != null) {
						try {
							fileInputStream.close();
						} catch (IOException e) {
						}
					}
				}
			}
		}

		Bitmap bitmap = null;
		if (fileDescriptor != null) {
			bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, width, height);
		}
		// end = System.currentTimeMillis();
		// Log.e(TAG + "287 time decode " + start, "" + (end - start));
		if (fileInputStream != null) {
			try {
				fileInputStream.close();
			} catch (IOException e) {
			}
		}
		return bitmap;
	}

	@Override
	protected Bitmap processBitmap(Object data, int width, int height, Bitmap bm) {
		return processBitmap(String.valueOf(data), width, height, bm);
	}

	/**
	 * Download a bitmap from a URL and write the content to an output stream.
	 * 
	 * @param urlString
	 *            The URL to fetch
	 * @return true if successful, false otherwise
	 */
	public boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
		// long start = System.currentTimeMillis();
		// Log.e("Start " + urlString, " " + start);
		// Log4m.i("" + urlString, "Start Download image", true, start);
		disableConnectionReuseIfNecessary();
		HttpURLConnection urlConnection = null;
		BufferedOutputStream out = null;
		BufferedInputStream in = null;

		boolean isError = false;

		try {

			final URL url = new URL(urlString);

			urlConnection = (HttpURLConnection) url.openConnection();
			if (urlConnection != null) {
				urlConnection.setConnectTimeout(20000);
				urlConnection.setReadTimeout(20000);
				arrConnections.add(urlConnection);
				in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
				out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);
				// long end1 = System.currentTimeMillis();
				// Log.e(TAG + " 334 time load stream " + start, "" + (end1 -
				// start));
				int b;
				while ((b = in.read()) != -1) {
					out.write(b);
				}

				// long end = System.currentTimeMillis();
				// Log.e(TAG + " 341 time load " + (end - start), "" +
				// urlString);
				// Log4m.i("" + urlString, "End Download image", true, start);
				arrConnections.remove(urlConnection);
				return true;
			} else {
				return false;
			}
		} catch (final IOException e) {
			Log.e(TAG + " 346", "Error in downloadBitmap - " + e);
			isError = true;
		} finally {
			if (isError) {
				Log.e("Loiiiiiiiiiiiiiiiii", ">''<");
				// downloadUrlToStream(urlString, outputStream);
			}
			if (urlConnection != null) {
				urlConnection.disconnect();
				arrConnections.remove(urlConnection);
			}
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (final IOException e) {
			}
		}
		return false;
	}

	public void downloadFile(String urlString, DialogListener dialogListener) {
		final String key = ImageCache.hashKeyForDisk(urlString);
		synchronized (mHttpDiskCacheLock) {
			// Wait for disk cache to initialize
			while (mHttpDiskCacheStarting) {
				try {
					mHttpDiskCacheLock.wait();
				} catch (InterruptedException e) {
				}
			}

			if (mHttpDiskCache != null) {
				try {
					DiskLruCache.Snapshot snapshot = mHttpDiskCache.get(key);
					if (snapshot == null) {
						// if (BuildConfig.DEBUG) {
						// Log.d(TAG,
						// "processBitmap, not found in http cache, downloading...");
						// }
						DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
						if (editor != null) {
							if (downloadUrlToStream(urlString, editor.newOutputStream(DISK_CACHE_INDEX))) {
								editor.commit();
							} else {
								editor.abort();
							}
						}
						snapshot = mHttpDiskCache.get(key);
					}
				} catch (IOException e) {
					Log.e(TAG, "processBitmap - " + e);
				} catch (IllegalStateException e) {
					Log.e(TAG, "processBitmap - " + e);
				} finally {
				}
			}
		}

	}

	/**
	 * Workaround for bug pre-Froyo, see here for more info:
	 * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
	 */
	public static void disableConnectionReuseIfNecessary() {
		// HTTP connection reuse which was buggy pre-froyo
		// if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
		// System.setProperty("http.keepAlive", "false");
		// }
	}

	public void displayImageUrlOnWebview(final WebView wv, final LinearLayout linearLayout, final String urlImage, final int width, final int height) {
		AsyncTask<String, String, String> asyn = new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
				Log.e("Display", urlImage);
				String pageData = "<img height=" + height + " width:auto src=\"" + urlImage + "\" />";
				String format = "" + "<div align=\"center\">" + pageData + "</div>";
				return format;
			}

			protected void onPostExecute(String format) {
				if (format != null) {
					final String urlStr = urlImage;
					final String mimeType = "text/html";
					final String encoding = null;
					final String f = format;
					if (wv != null) {

						wv.setVisibility(View.GONE);
						wv.clearHistory();
						wv.clearCache(true);
						wv.clearSslPreferences();
						wv.getSettings().setBuiltInZoomControls(false);
						wv.getSettings().setJavaScriptEnabled(true);
						// wv.getSettings().setLightTouchEnabled(true);
						wv.setVisibility(View.VISIBLE);
						if (linearLayout != null)
							linearLayout.setVisibility(View.GONE);
						wv.setWebChromeClient(new WebChromeClient() {
							public void onProgressChanged(WebView view, int progress) {
								// if (progress == 100) {
								// wv.setVisibility(View.VISIBLE);
								// linearLayout.setVisibility(View.GONE);
								// } else {
								// if (linearLayout.getVisibility() ==
								// View.GONE) {
								// linearLayout.setVisibility(View.VISIBLE);
								// }
								// }

							}

						});
						if (ConfigUtility.os_version >= 11) {
							wv.setLayerType(View.LAYER_TYPE_SOFTWARE, new Paint());
						}
						wv.setBackgroundColor(0x00000000);
						mContext.runOnUiThread(new Runnable() {

							public void run() {
								wv.loadDataWithBaseURL(urlStr, f, mimeType, encoding, urlStr);
							}
						});
					}

				}
			}
		};
		asyn.execute();

	}

	public void clearConnections() {
		for (HttpURLConnection httpURLConnection : arrConnections) {
			httpURLConnection.disconnect();
		}
		arrConnections.clear();
	}
}
